package com.gome.gop.mybatis.rw.datasource;

import java.util.HashMap;
import java.util.Map;

import org.apache.tomcat.jdbc.pool.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 读写分离，数据源切换
 * 
 * @file DynamicDataSourceHolder.java
 * @tags
 * @copyright gome.com.cn @ copyright
 * @date 2018年2月7日 下午6:16:46
 * @author jiangdabin
 */
public class DynamicDataSourceHolder {
	private static final ThreadLocal<DynamicDataSourceGlobal> holder = new ThreadLocal<DynamicDataSourceGlobal>();
	private static Logger logger = LoggerFactory.getLogger(DynamicDataSourceHolder.class);
	public static Map<String, DataSource> dataSources = new HashMap<String, DataSource>();
	public static DataSource writeDataSources = null;

	/**
	 * 按名称指定数据源
	 */

	public static void setDataSource(String name) {
		logger.debug("手动设置数据源为：{}", name);
		DynamicDataSourceGlobal dataSource = DynamicDataSourceGlobal.builderHand(name);
		holder.set(dataSource);
	}

	/**
	 * <b>读写分离数据源设定</b>
	 * <p>
	 * </p>
	 * 
	 * @param dataSource
	 */
	public static void setDataSource(DynamicDataSourceGlobal dataSource) {
		if (dataSource == null) {
			logger.warn("数据源设定方式为空，直接退出，将强制使用主库");
			return;
		}
		holder.set(dataSource);
	}

	public static DynamicDataSourceGlobal getDataSource() {
		// logger.debug("获取数据数据源为：{}");
		return holder.get();
	}

	/**
	 * 清空使用的数据源
	 */
	public static void clearDataSource() {
		holder.remove();
	}
}
